// pages/shoopingCart/shoopingCart.js
const api = require("../../utils/request");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    num: 0,
    checkedAll: false,
  },

  selectAll(e) {
    const checkedAll = e.detail.value[0] === 'all';

    this.setData({
      checkedAll: checkedAll,
      list: this.data.list.map(item => {
        item.checked = checkedAll;
        return item;
      })
    });

    this.calculateTotal();
  },

  checkboxChange(e) {
    const id = e.detail.value[0];
    const list = this.data.list;

    if (id !== undefined && id !== '') {
      const index = list.findIndex(item => String(item.id) === String(id));
      if (index !== -1) {
        list[index].checked = !list[index].checked;
      }
    } else {
      const index = list.findIndex(item => String(item.id) === String(e.currentTarget.dataset.id));
      if (index !== -1) {
        list[index].checked = !list[index].checked;
      }
    }

    const allChecked = list.every(item => item.checked);

    this.setData({
      list: list,
      checkedAll: allChecked
    });

    this.calculateTotal();
  },

  calculateTotal() {
    const result = this.data.list.reduce((acc, item) => {
      if (item.checked) {
        acc.totalPrice += parseFloat(item.price) * item.num;
        acc.totalQuantity += item.num;
      }
      return acc;
    }, {
      totalPrice: 0,
      totalQuantity: 0
    });

    this.setData({
      num: result.totalPrice.toFixed(2),
      totalQuantity: result.totalQuantity
    });
  },

  changeQuantity(e) {
    const {
      index,
      quantity
    } = e.detail;
    const list = this.data.list;
    list[index].num = quantity;

    this.setData({
      list: list
    });

    this.calculateTotal();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (wx.getStorageSync('loginState')) {
      api.petList({
        data: {
          pageNum: 1,
          pageSize: 999
        }
      }).then(res => {
        const list = res.data.data.records.map(item => {
          return {
            ...item,
            checked: false,
            num: 1
          };
        });

        this.setData({
          list: list
        });

        this.calculateTotal();
      });
    } else {
      this.setData({
        list: [],
        checkedAll: false,
        num: 0.00
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.onLoad()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});